package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.OutApplicationSettingConvert;
import com.engine4cloud.tdf.supervision.dto.create.OutApplicationSettingCreateDTO;
import com.engine4cloud.tdf.supervision.dto.result.OutApplicationSettingResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.OutApplicationSettingUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.OutApplicationSettingEntity;
import com.engine4cloud.tdf.supervision.mapper.OutApplicationSettingMapper;
import com.engine4cloud.tdf.supervision.service.OutApplicationSettingService;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

/**
 * 外出申请配置表
 *
 * @author wenjie
 * @date 2024-09-24 15:52:53
 */
@Service
public class OutApplicationSettingServiceImpl extends ServiceImpl<OutApplicationSettingMapper, OutApplicationSettingEntity> implements OutApplicationSettingService {
    @Override
    public OutApplicationSettingResultDTO findFirst() {
        return findDefaultSetting();
    }

    @Override
    public OutApplicationSettingResultDTO findDefaultSetting() {
        return OutApplicationSettingConvert.INSTANCE.convert(super.list().stream().findFirst().orElse(null));
    }

    @Override
    public Boolean create(OutApplicationSettingCreateDTO dto) {
        OutApplicationSettingResultDTO exist = this.findFirst();
        if (Objects.nonNull(exist)) {
            throw new ValidateCodeException("数据已存在");
        }

        return super.save(OutApplicationSettingConvert.INSTANCE.create(dto, SecurityUtils.getUser().getTenantId()));
    }

    @Override
    public Boolean update(OutApplicationSettingUpdateDTO dto) {
        Optional.ofNullable(super.getById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        return super.updateById(OutApplicationSettingConvert.INSTANCE.update(dto));
    }
}